package com.zepher.springboot.service;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zepher.springboot.entity.Account;
import com.zepher.springboot.entity.User;
import com.zepher.springboot.exception.CustomException;
import com.zepher.springboot.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.Period;
import java.util.List;

@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 查询所有用户
     * @param user
     * @return
     */
    public List<User> selectAll(User user) {
        List<User> list = userMapper.selectAll(user);
        return list;
    }

    /**
     * 根据用户ID查询单个用户
     * @param id 用户ID
     * @return
     */
    public User selectById(Integer id) {
        User user = userMapper.selectById(id);
        return user;
    }

    /**
     * 分页查询
     */
    public PageInfo<User> selectPage(Integer pageNum, Integer pageSize, User user) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userMapper.selectAll(user);
        PageInfo<User> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 新增用户
     */
    public void insert(User user) {
        String username = user.getUsername();
        String email = user.getEmail();
        String phone = user.getPhone();
        String idCard = user.getIdCard();
        User dbUser = userMapper.selectByUsername(username);
        if (dbUser != null) {
            throw new CustomException("500", "用户已存在");
        }
        dbUser = userMapper.selectByEmail(email);
        if (dbUser != null) {
            throw new CustomException("500", "邮箱已存在");
        }
        dbUser = userMapper.selectByPhone(phone);
        if (dbUser != null) {
            throw new CustomException("500", "手机号已存在");
        }
        dbUser = userMapper.selectByIdCard(idCard);
        if (dbUser != null) {
            throw new CustomException("500", "身份证号已存在");
        }
        if (StrUtil.isBlank(user.getPassword())){
            user.setPassword("123456");
        }
        if (StrUtil.isBlank(user.getName())){
            user.setName(user.getUsername());
        }
        if (StrUtil.isBlank(user.getRole())){
            user.setRole("user");
        }
        if (StrUtil.isBlank(user.getSex())){
            user.setSex(idCard.charAt(16) == 'X' ? "女" : "男");
        }
        if (user.getAge() == null){
            user.setAge(Integer.parseInt(idCard.substring(6, 10)));
            try {
                //  提取出生日期（第7-14位）
                String birthStr = idCard.substring(6, 14); // 注意：substring(endIndex是 exclusive)
                int year = Integer.parseInt(birthStr.substring(0, 4));
                int month = Integer.parseInt(birthStr.substring(4, 6));
                int day = Integer.parseInt(birthStr.substring(6, 8));

                //  转换为LocalDate（自动校验日期合法性，如2月30日会抛异常）
                LocalDate birthDate = LocalDate.of(year, month, day);
                LocalDate today = LocalDate.now(); // 当前日期

                //  计算年龄（Period计算年月日差值）
                Period period = Period.between(birthDate, today);
                int age = period.getYears();

                //  若当前月份小于出生月份，或月份相同但日期小于出生日期，年龄减1
                if (period.getMonths() < 0 || (period.getMonths() == 0 && period.getDays() < 0)) {
                    age--;
                }
                // 防止出生日期在未来
                if (age < 0) {
                    throw new CustomException("500", "身份证有误，出生日期在未来");
                }
                user.setAge(age);
            } catch (Exception e) {
                // 处理日期格式错误（如月份13、日期32等）
                throw new CustomException("500", "身份证号格式错误");
            }
        }
        userMapper.insert(user);
    }

    /**
     * 修改用户
     */
    public void update(User user) {
        userMapper.update(user);
    }

    /**
     * 删除用户
     */
    public void delete(Integer id) {
        userMapper.delete(id);
    }

    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            userMapper.delete(id);
        }
    }

    /**
     * 登录
     */
    public User login(Account account) {
        String username = account.getUsername();
        User dbUser = userMapper.selectByUsername(username);
        if (dbUser == null) {
            throw new CustomException("500", "用户不存在");
        }
        // 数据库存在这个账号
        String password = account.getPassword();
        if (!dbUser.getPassword().equals(password)) {
            throw new CustomException("500", "账号或密码错误");
        }
        return dbUser;
    }

    public void register(User user) {
        this.insert(user);
    }
}
